/**
 * xmlconnector.cpp is part of %PROJECTNAME%.
 *
 * %PROJECTNAME% is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * %PROJECTNAME% is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with %PROJECTNAME%.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "xmlconnector.h"
#include <QFile>
#include "../../utils/logging/logmanager.h"
#include "../../utils/logging/logger.h"

XmlConnector::XmlConnector( const std::string & a_file ) :
    Connector(),
    m_file( a_file ),
    m_xmlStream()
{
}

bool XmlConnector::Load()
{
    Logger * log = GET_LOG_MGR().GetLogger( "LOG" );
    if( log )
        log->LogInfo() << "---- Loading XML file: " << m_file << " ----";

    QFile file( QString( m_file.c_str() ) );
    if ( !file.open( QFile::ReadOnly | QFile::Text ) )
    {
        if( log )
            log->LogError() << "Cannot open file " << m_file;

        return false;
    }

    m_xmlStream.setDevice( &file );

    while( !m_xmlStream.atEnd() )
    {
        ReadElement( m_xmlStream.readNext(), m_xmlStream );
    }

    if( m_xmlStream.hasError() )
    {
        HandleError( m_xmlStream );
        return false;
    }

    if( log )
        log->LogInfo() << "---- XML file: " << m_file << " loaded ----";

    file.close();

    return true;
}

const std::string & XmlConnector::File()
{
    return m_file;
}

const QXmlStreamReader & XmlConnector::XmlStream()
{
    return m_xmlStream;
}

bool XmlConnector::IsStartElement( QXmlStreamReader::TokenType a_type )
{
    return a_type == QXmlStreamReader::StartElement;
}

bool XmlConnector::IsEndElement( QXmlStreamReader::TokenType a_type )
{
    return a_type == QXmlStreamReader::EndElement;
}
